package com.cy.module.dingtalk.pc;

import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Device;
import com.cy.model.UserRemarkInfo;
import com.cy.module.WebApiController;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/dingtalk/pc/userRemarkInfo")
public class UserRemarkInfoController extends WebApiController {
    
    @Override
    public void index() {
        UserRemarkInfo userRemarkInfo = getModel(UserRemarkInfo.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Map<String, String[]> parasMap = getParaMap();
        if (null != parasMap){
            String start ;
            if(null != parasMap.get("start_time")){
                start = parasMap.get("start_time")[0];
                if (StringUtils.isNotBlank(start))
                    userRemarkInfo.put("start",start);
            }
            String end;
            if (null != parasMap.get("end_time")){
                end = parasMap.get("end_time")[0];
                if (StringUtils.isNotBlank(end))
                    userRemarkInfo.put("end",end);
            }
        }
        Page<UserRemarkInfo> userRemarkInfoPage = UserRemarkInfo.dao.paginate(page, pageSize, UserRemarkInfo.SELECT_ALL, userRemarkInfo);
        for (UserRemarkInfo temp : userRemarkInfoPage.getList()){
            temp.put("user", temp.getUser());
            temp.put("account", temp.getAccount());
            temp.put("device", temp.getDevice());
        }
        renderBuiPage(userRemarkInfoPage, 200);
    }

    @Override
    public void update() {
        int id = getParaToInt();
        UserRemarkInfo tempUserRemarkInfo = getModel(UserRemarkInfo.class);
        UserRemarkInfo userRemarkInfo = UserRemarkInfo.dao.findById(id);
        userRemarkInfo.cover(tempUserRemarkInfo);

        if (userRemarkInfo.update()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void save() {
        UserRemarkInfo userRemarkInfo = getModel(UserRemarkInfo.class);
        Long deviceId = userRemarkInfo.getDeviceId();
        if (deviceId != null){
            if (Device.dao.findById(deviceId) == null){
                renderFail("设备ID不存在！");
                return;
            }
        }
        userRemarkInfo.setCreateTime(new Date());
        userRemarkInfo.setAccountId(getLoginAccount().getAccountId());
        if (userRemarkInfo.save()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void delete() {
        String[] ids = getPara().split("-");
        for (String id : ids) {
            UserRemarkInfo.dao.deleteById(id);
        }
        renderSuccess();
    }
}